<?php
namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Resources\AdminResource;
use App\Model\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

/**
 * Created by PhpStorm.
 * User: 都大爽
 * Date: 2017/8/24
 * Time: 11:26
 */

class AuthController extends Controller
{

    /**
     * 登录
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|mixed|\Symfony\Component\HttpFoundation\Response
     */
    public function login(Request $request)
    {

//        dd($request);
        $validator = Validator::make($request->all(), [
            'username' => 'required',
            'password' => 'required'
        ],[
            'username.required' => '用户名必填',
            'username.exists' => '用户名不存在',
            'password.required' => '密码必填'
        ]);
        if ($validator->fails()) {
            return response($validator->errors()->toArray(), 401);
        }
            $user = User::where('username', $request->get('username'))->first();

//        dd($user);
//            $user->api_token = str_random(60);
        if (!$user){
            return response()->json(['message'=>'用户不存在'],461);
        }
        if(!\Hash::check($request->get('password'),$user->password)){
            return response()->json(['message'=>'密码错误'],461);
        }
            Auth::login($user);
//        $user->save();
          return new AdminResource($user);

    }
}
